<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>专用线程 Dedicated Worker —— Inline Worker(Blob)</title>
</head>

<body>
    <h3>专用线程 Dedicated Worker —— Inline Worker(Blob)</h3>
    <script id="myWorker" type="javascript/worker">
    self['onmessage'] = function(event) {
        postMessage('Hello, ' + event.data.name + '!');
    };
    </script>
    <script>
        if (window.Worker) {
            // 第一种方法，通过blob格式创建worker
            /* const url = URL.createObjectURL(
                new Blob([`postMessage("Dedicated Worker created by Blob")`])
            );
            let worker = new Worker(url);
            worker.onmessage = (e) =>
            console.log(`Main: Received message - ${e.data}`); */
            // 第二种方法，通过blob格式创建worker，通过设置type="javascript/worker"
            let workerScript = document.querySelector('#myWorker').textContent;
            let blob = new Blob([workerScript], {
                type: "text/javascript"
            });
            let worker = new Worker(URL.createObjectURL(blob));
            worker.postMessage({
                name: "Dedicated Worker"
            });
            worker.onmessage = (e) =>
            console.log(`Main: Received Blob message - ${e.data}`);
        } else {
            console.log("呜呜呜，不支持 Web Worker");
        }
    </script>
</body>

</html>